<template>
  <div class="videos-container">
    <el-card>
      <!-- 搜索和筛选区域 -->
      <div class="search-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="searchForm.title"
              placeholder="请输入视频标题"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-select
              v-model="searchForm.status"
              placeholder="审核状态"
              clearable
            >
              <el-option label="全部" value="" />
              <el-option label="待审核" value="pending" />
              <el-option label="已通过" value="approved" />
              <el-option label="已拒绝" value="rejected" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select
              v-model="searchForm.category"
              placeholder="课程分类"
              clearable
            >
              <el-option label="全部" value="" />
              <el-option label="前端开发" value="frontend" />
              <el-option label="后端开发" value="backend" />
              <el-option label="数据科学" value="data" />
              <el-option label="人工智能" value="ai" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-col>
          <!-- <el-col :span="4">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-col> -->
        </el-row>
        <el-row :gutter="20" style="margin-top: 15px;">
          <el-col :span="24" style="text-align: right;">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 统计卡片 -->
      <div class="stats-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ stats.total }}</div>
                <div class="stat-label">总视频数</div>
              </div>
              <el-icon class="stat-icon total"><VideoCamera /></el-icon>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ stats.pending }}</div>
                <div class="stat-label">待审核</div>
              </div>
              <el-icon class="stat-icon pending"><Clock /></el-icon>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ stats.approved }}</div>
                <div class="stat-label">已通过</div>
              </div>
              <el-icon class="stat-icon approved"><Check /></el-icon>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ stats.rejected }}</div>
                <div class="stat-label">已拒绝</div>
              </div>
              <el-icon class="stat-icon rejected"><Close /></el-icon>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 批量操作 -->
      <div class="batch-actions">
        <el-button
          type="success"
          :disabled="!multipleSelection.length"
          @click="batchApprove"
        >
          批量通过
        </el-button>
        <el-button
          type="danger"
          :disabled="!multipleSelection.length"
          @click="batchReject"
        >
          批量拒绝
        </el-button>
        <el-button
          type="warning"
          :disabled="!multipleSelection.length"
          @click="batchDelete"
        >
          批量删除
        </el-button>
        <span class="selection-info">
          已选择 {{ multipleSelection.length }} 项
        </span>
      </div>

      <!-- 视频列表表格 -->
      <el-table
        :data="videoList"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        stripe
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column label="视频信息" width="300">
          <template #default="{ row }">
            <div class="video-info">
              <div class="video-thumbnail">
                <img :src="row.thumbnail" :alt="row.title" />
                <div class="video-duration">{{ row.duration }}</div>
              </div>
              <div class="video-details">
                <div class="video-title">{{ row.title }}</div>
                <div class="video-author">{{ row.author }}</div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="category" label="分类" width="120">
          <template #default="{ row }">
            <el-tag size="small">{{ getCategoryName(row.category) }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="uploadTime" label="上传时间" width="180" />

        <el-table-column label="审核状态" width="120">
          <template #default="{ row }">
            <el-tag
              :type="getStatusType(row.status)"
              size="small"
            >
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="views" label="观看次数" width="100" />

        <el-table-column prop="rating" label="评分" width="100">
          <template #default="{ row }">
            <el-rate
              v-model="row.rating"
              disabled
              size="small"
              show-score
              text-color="#ff9900"
            />
          </template>
        </el-table-column>

        <el-table-column label="审核信息" width="200">
          <template #default="{ row }">
            <div v-if="row.reviewInfo">
              <div class="review-info">
                <div>审核人：{{ row.reviewInfo.reviewer }}</div>
                <div>审核时间：{{ row.reviewInfo.reviewTime }}</div>
                <div v-if="row.reviewInfo.reason" class="review-reason">
                  拒绝理由：{{ row.reviewInfo.reason }}
                </div>
              </div>
            </div>
            <span v-else class="text-muted">暂无审核信息</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handlePreview(row)"
            >
              预览
            </el-button>
            
            <el-button
              v-if="row.status === 'pending'"
              type="success"
              size="small"
              @click="handleApprove(row)"
            >
              通过
            </el-button>
            
            <el-button
              v-if="row.status === 'pending'"
              type="danger"
              size="small"
              @click="handleReject(row)"
            >
              拒绝
            </el-button>
            
            <el-dropdown v-else>
              <el-button size="small">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleEdit(row)">编辑</el-dropdown-item>
                  <el-dropdown-item v-if="row.status === 'approved'" @click="handleRevoke(row)">撤销通过</el-dropdown-item>
                  <el-dropdown-item v-if="row.status === 'rejected'" @click="handleReApprove(row)">重新审核</el-dropdown-item>
                  <el-dropdown-item divided @click="handleDelete(row)">删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="视频预览"
      width="800px"
      @close="handlePreviewClose"
    >
      <div class="video-preview" v-if="currentVideo">
        <video
          :src="currentVideo.videoUrl"
          controls
          width="100%"
          height="400px"
        ></video>
        <div class="video-meta">
          <h3>{{ currentVideo.title }}</h3>
          <p>{{ currentVideo.description }}</p>
          <div class="meta-info">
            <span>作者：{{ currentVideo.author }}</span>
            <span>时长：{{ currentVideo.duration }}</span>
            <span>分类：{{ getCategoryName(currentVideo.category) }}</span>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 审核拒绝对话框 -->
    <el-dialog
      v-model="rejectVisible"
      title="审核拒绝"
      width="500px"
    >
      <el-form :model="rejectForm" ref="rejectFormRef" :rules="rejectRules">
        <el-form-item label="拒绝理由" prop="reason">
          <el-input
            v-model="rejectForm.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入拒绝理由"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="rejectVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmReject">确认拒绝</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 图标导入（需要在实际项目中正确导入）
// import { Search, VideoCamera, Clock, Check, Close, ArrowDown } from '@element-plus/icons-vue'

// 搜索表单
const searchForm = reactive({
  title: '',
  status: '',
  category: '',
  dateRange: []
})

// 统计数据
const stats = reactive({
  total: 156,
  pending: 23,
  approved: 120,
  rejected: 13
})

// 表格数据
const loading = ref(false)
const videoList = ref([
  {
    id: 1,
    title: 'Vue 3 入门教程',
    author: '张老师',
    category: 'frontend',
    thumbnail: 'https://via.placeholder.com/120x80?text=Vue3',
    duration: '15:30',
    uploadTime: '2024-03-15 10:30:00',
    status: 'pending',
    views: 1250,
    rating: 4.5,
    videoUrl: 'https://example.com/video1.mp4',
    description: 'Vue 3 框架基础入门教程，适合初学者学习...',
    reviewInfo: null
  },
  {
    id: 2,
    title: 'React Hooks 深入解析',
    author: '李教授',
    category: 'frontend',
    thumbnail: 'https://via.placeholder.com/120x80?text=React',
    duration: '25:45',
    uploadTime: '2024-03-14 14:20:00',
    status: 'approved',
    views: 2340,
    rating: 4.8,
    videoUrl: 'https://example.com/video2.mp4',
    description: 'React Hooks 的深入讲解和实战应用...',
    reviewInfo: {
      reviewer: '管理员A',
      reviewTime: '2024-03-14 16:30:00',
      reason: null
    }
  },
  {
    id: 3,
    title: 'Node.js 后端开发',
    author: '王工程师',
    category: 'backend',
    thumbnail: 'https://via.placeholder.com/120x80?text=Node.js',
    duration: '32:15',
    uploadTime: '2024-03-13 09:15:00',
    status: 'rejected',
    views: 0,
    rating: 0,
    videoUrl: 'https://example.com/video3.mp4',
    description: 'Node.js 服务端开发实战教程...',
    reviewInfo: {
      reviewer: '管理员B',
      reviewTime: '2024-03-13 15:45:00',
      reason: '内容质量不符合平台标准，建议重新录制'
    }
  }
])

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 156
})

// 多选
const multipleSelection = ref([])

// 预览相关
const previewVisible = ref(false)
const currentVideo = ref(null)

// 拒绝审核相关
const rejectVisible = ref(false)
const rejectForm = reactive({
  reason: ''
})
const rejectFormRef = ref()
const rejectRules = {
  reason: [
    { required: true, message: '请输入拒绝理由', trigger: 'blur' }
  ]
}
const currentRejectVideo = ref(null)

// 方法
const handleSearch = () => {
  loading.value = true
  // 搜索逻辑
  setTimeout(() => {
    loading.value = false
    ElMessage.success('搜索完成')
  }, 1000)
}

const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'dateRange' ? [] : ''
  })
  handleSearch()
}

const handleSelectionChange = (selection) => {
  multipleSelection.value = selection
}

const batchApprove = () => {
  ElMessageBox.confirm(
    `确定要批量通过选中的 ${multipleSelection.value.length} 个视频吗？`,
    '批量通过',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage.success('批量通过成功')
  })
}

const batchReject = () => {
  ElMessageBox.prompt('请输入拒绝理由', '批量拒绝', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputType: 'textarea',
    inputValidator: (value) => {
      if (!value) return '请输入拒绝理由'
      return true
    }
  }).then(({ value }) => {
    ElMessage.success('批量拒绝成功')
  })
}

const batchDelete = () => {
  ElMessageBox.confirm(
    `确定要删除选中的 ${multipleSelection.value.length} 个视频吗？此操作不可恢复！`,
    '批量删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    }
  ).then(() => {
    ElMessage.success('批量删除成功')
  })
}

const handlePreview = (row) => {
  currentVideo.value = row
  previewVisible.value = true
}

const handlePreviewClose = () => {
  currentVideo.value = null
}

const handleApprove = (row) => {
  ElMessageBox.confirm(
    `确定要通过视频「${row.title}」的审核吗？`,
    '审核通过',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'success'
    }
  ).then(() => {
    row.status = 'approved'
    row.reviewInfo = {
      reviewer: '当前管理员',
      reviewTime: new Date().toLocaleString(),
      reason: null
    }
    ElMessage.success('审核通过')
  })
}

const handleReject = (row) => {
  currentRejectVideo.value = row
  rejectVisible.value = true
}

const confirmReject = () => {
  rejectFormRef.value.validate((valid) => {
    if (valid) {
      currentRejectVideo.value.status = 'rejected'
      currentRejectVideo.value.reviewInfo = {
        reviewer: '当前管理员',
        reviewTime: new Date().toLocaleString(),
        reason: rejectForm.reason
      }
      rejectVisible.value = false
      rejectForm.reason = ''
      currentRejectVideo.value = null
      ElMessage.success('审核拒绝成功')
    }
  })
}

const handleEdit = (row) => {
  ElMessage.info('跳转到编辑页面')
}

const handleRevoke = (row) => {
  ElMessageBox.confirm(
    `确定要撤销视频「${row.title}」的审核通过状态吗？`,
    '撤销通过',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    row.status = 'pending'
    row.reviewInfo = null
    ElMessage.success('已撤销审核通过状态')
  })
}

const handleReApprove = (row) => {
  row.status = 'pending'
  row.reviewInfo = null
  ElMessage.success('已重置为待审核状态')
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除视频「${row.title}」吗？此操作不可恢复！`,
    '删除视频',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    }
  ).then(() => {
    const index = videoList.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      videoList.value.splice(index, 1)
    }
    ElMessage.success('删除成功')
  })
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  handleSearch()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  handleSearch()
}

// 工具方法
const getCategoryName = (category) => {
  const categoryMap = {
    frontend: '前端开发',
    backend: '后端开发',
    data: '数据科学',
    ai: '人工智能'
  }
  return categoryMap[category] || category
}

const getStatusType = (status) => {
  const typeMap = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger'
  }
  return typeMap[status] || ''
}

const getStatusText = (status) => {
  const textMap = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已拒绝'
  }
  return textMap[status] || status
}

onMounted(() => {
  handleSearch()
})
</script>

<style scoped>
.videos-container {
  padding: 20px;
}

/* 搜索区域 */
.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

/* 统计卡片 */
.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-content {
  padding: 10px 0;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.stat-icon {
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 40px;
  opacity: 0.3;
}

.stat-icon.total { color: #409EFF; }
.stat-icon.pending { color: #E6A23C; }
.stat-icon.approved { color: #67C23A; }
.stat-icon.rejected { color: #F56C6C; }

/* 批量操作 */
.batch-actions {
  margin-bottom: 20px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.selection-info {
  color: #606266;
  font-size: 14px;
  margin-left: auto;
}

/* 视频信息 */
.video-info {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.video-thumbnail {
  position: relative;
  flex-shrink: 0;
}

.video-thumbnail img {
  width: 120px;
  height: 80px;
  object-fit: cover;
  border-radius: 6px;
}

.video-duration {
  position: absolute;
  bottom: 4px;
  right: 4px;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 12px;
}

.video-details {
  flex: 1;
  min-width: 0;
}

.video-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.video-author {
  font-size: 12px;
  color: #909399;
}

/* 审核信息 */
.review-info {
  font-size: 12px;
  color: #606266;
  line-height: 1.4;
}

.review-reason {
  color: #F56C6C;
  margin-top: 4px;
}

.text-muted {
  color: #C0C4CC;
  font-size: 12px;
}

/* 分页 */
.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 预览对话框 */
.video-preview {
  text-align: center;
}

.video-meta {
  margin-top: 20px;
  text-align: left;
}

.video-meta h3 {
  margin: 0 0 10px 0;
  color: #303133;
}

.video-meta p {
  color: #606266;
  margin: 0 0 15px 0;
  line-height: 1.5;
}

.meta-info {
  display: flex;
  gap: 20px;
  font-size: 14px;
  color: #909399;
}

/* 响应式 */
@media (max-width: 768px) {
  .search-section .el-row {
    flex-direction: column;
  }
  
  .search-section .el-col {
    margin-bottom: 10px;
  }
  
  .stats-section .el-col {
    margin-bottom: 10px;
  }
  
  .batch-actions {
    flex-wrap: wrap;
  }
  
  .video-info {
    flex-direction: column;
  }
  
  .video-thumbnail {
    align-self: center;
  }
}
</style>